/*
 * Antichat Web Tool
 *
 * [C] Great, Antichat.
 *
 * http://antichat.ru
 *
 *
 * Source: socks
 */

/*
 * SOCKS class
 *
 * (C) Great, 2006
 */

#include "socket.h"
#include "socks.h"

// Save proxy info
void Socks::set_proxy(char* proxy_host, int proxy_port)
{
	this->proxy_host = proxy_host;
	this->proxy_port = proxy_port;
}

// Connect to SOCKS
int Socks::connect(char* dest_host, int dest_port)
{
	set_terminate_flag(0);
	if(Socket::connect(proxy_host, proxy_port)==-1)
		return -1;
	
	unsigned char packet[1024];
	int bytes=0;

	memcpy(packet, "\x05\x01\x00", 3);
	send(packet, 3);
	recv(packet, sizeof(packet));
	bytes = get_last_length();

	if(*(WORD*)packet != 0x0005)
	{
		close();
		return -1;
	}

	DWORD ip = nslookup_raw(dest_host);
	if(!ip)
	{
		close();
		return -1;
	}

	packet[0] = 5; // VERSION: 5
	packet[1] = 1; // METHOD: CONNECT
	packet[2] = 0; // RSV: 0
	packet[3] = 1; // ADTYPE: IPv4
	*(DWORD*)&(packet[4]) = ip;
	*(WORD*)&(packet[8])  = htons(dest_port);

	send(packet, 10);
	recv(packet, sizeof(packet));
	bytes = get_last_length();

	if(bytes!=10 || packet[1])
	{
		close();
		return -1;
	}

	set_terminate_flag(1);
	
	return 0;
}